package Cantella::DJabberd::Store::Result::JabberGroupJid;

use base qw'DBIx::Class::Core';
use metaclass 'Reaction::Meta::Class';
use Moose;

use aliased 'Cantella::DJabberd::Store::Result::UserJid';
use aliased 'Cantella::DJabberd::Store::Result::JabberGroup';

use namespace::clean -except => [ 'meta' ];

__PACKAGE__->table('jabber_group_jids');
__PACKAGE__->add_columns
  (
   jid_id => {
              data_type => "INT",
              size => 10,
              is_nullable => 0,
              extra => { unsigned => 1 },
              is_foreign_key => 1,
             },
   group_id => {
                data_type => "INT",
                size => 10,
                is_nullable => 0,
                extra => { unsigned => 1 },
                is_foreign_key => 1,
               },
  );

__PACKAGE__->set_primary_key(qw/group_id jid_id/);

__PACKAGE__->belongs_to(user_jid => UserJid, { id => "jid_id" });
__PACKAGE__->belongs_to(jabber_group => JabberGroup, { id => "group_id" });


sub insert {
  my $self = shift;
  $self = $self->next::method(@_);
  my $user = $self->user_jid;
  my $group = $self->jabber_group;

  my $owner_rg = $user->roster_groups->find_or_create({ name => $group->name });
  for my $jid ($group->user_jids){
    #don't add self to roster
    next if $jid->id == $user->id;
    #create the entry on the new contact's side
    my $contact_rg = $jid->roster_groups->find_or_create({ name => $group->name });
    my $contact_ri = $jid->roster_items->find_or_create
      ({
        contact => $user,
        name => $user->user->full_name,
        subscription => 3,
       });
    $contact_rg->add_to_roster_items($contact_ri)
      unless $contact_rg->roster_items->find({ id => $contact_ri->id });

    #create the entry on the current user's side
    my $owner_ri = $user->roster_items->find_or_create
        ({
          contact => $jid,
          name => $jid->user->full_name,
          subscription => 3,
         });
    $owner_rg->add_to_roster_items($owner_ri)
      unless $owner_rg->roster_items->find({ id => $owner_ri->id });
  }

  return $self;
};

__PACKAGE__->meta->make_immutable(inline_constructor => 0);

1;
